package myicesscheduler.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

public class LoginController extends SimpleFormController
{
   protected final Log logger = LogFactory.getLog( getClass() );
   public final static String attr_isAdmin = "login_isAdmin";
   public final static String attr_isLoggedIn = "login_isLoggedIn";
   public final static String param_logout = "login_logout";

   public ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response )
         throws Exception
   {
      final String logoutURL = request.getParameter( param_logout );
      if( null == logoutURL )
         return handleRequest_login( request, response );
      else
         return handleRequest_logout( request, response, logoutURL );
   }

   private ModelAndView handleRequest_login( HttpServletRequest request,
         HttpServletResponse response ) throws Exception
   {
      setToBeLoggedIn( request.getSession() );
      final ModelAndView mv = super.handleRequest( request, response );
      return mv;
   }

   private ModelAndView handleRequest_logout( HttpServletRequest request,
         HttpServletResponse response, String logoutURL )
   {
      setToBeLoggedOut( request.getSession() );
      return new ModelAndView( new RedirectView( logoutURL ) );
   }

   public static void setToBeLoggedIn( HttpSession session )
   {
      session.setAttribute( attr_isLoggedIn, "true" );
      setToBeAdmin( session );
   }

   public static void setToBeAdmin( HttpSession session )
   {
      session.setAttribute( attr_isAdmin, "true" );
   }

   public static void setToBeLoggedOut( HttpSession session )
   {
      session.setAttribute( attr_isAdmin, null );
      session.setAttribute( attr_isLoggedIn, null );
   }

   public static boolean isLoggedIn( HttpServletRequest request )
   {
      return null != request.getSession().getAttribute( attr_isLoggedIn );
   }

   public static boolean isAdmin( HttpServletRequest request )
   {
      return null != request.getSession().getAttribute( attr_isAdmin );
   }

   @Override
   protected ModelAndView onSubmit( Object command ) throws Exception
   {
      if( null == command ) logger.info( "onSubmit: command object is null" );
      final LoginCommand cmd = (LoginCommand) command;
      logger.info( "onSubmit: " + cmd.toString() );

      final ModelAndView mv = new ModelAndView( this.getSuccessView() );
      return mv;
   }

   @Override
   protected Object formBackingObject( HttpServletRequest request ) throws Exception
   {
      final LoginCommand cmd = new LoginCommand();
      return cmd;
   }
}
